<?php

namespace app\admin\builder;
use peter\util\pagination\Pagination;
use think\Url;
vendor('wechat/autoload','php');
class ListBuilder extends AdminBuilder  {
    private $_keyList = [];
    private $_buttonList = [];
    private $_pagination;
    private $_data = [];
    private $_searchUrl;
    private $_searchList = [];
    private $_selectUrl;
    private $_selectList = [];


    public function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        // 编译按钮attr
        foreach ($this->_buttonList as &$button) {
            $button['attr'] = $this->compileHtmlAttr($button['attr']);
        }

        // 编译doAction的attr
        foreach ($this->_keyList as &$key) {
            if($key['type'] == 'doAction') {
                foreach ($key['opt']['actions'] as &$action) {
                    $action['attr'] = $this->compileHtmlAttr($action['attr']);
                }
                break;
            }
        }



        $this->assign("_data",$this->_data);
        $this->assign("_keyList",$this->_keyList);
        $this->assign("_buttonList",$this->_buttonList);
        $this->assign("_pagination",$this->_pagination);
        $this->assign("_searchUrl",$this->_searchUrl);
        $this->assign("_searchList",$this->_searchList);
        $this->assign("_selectUrl",$this->_selectUrl);
        $this->assign("_selectList",$this->_selectList);
        return parent::fetch("list_builder", $vars, $replace, $config);
    }

    public function data($data) {
        $this->_data = $data;
        return $this;
    }

    public function key($name, $title, $type, $opt = null)
    {
        $key = [
            'name' => $name,
            'title' => $title,
            'type' => $type,
            'opt' => $opt,
        ];
        $this->_keyList[] = $key;
        return $this;
    }

    /**
     * @param $name
     * @param $title
     * @param null $map 例如: ['已安装'=>true,'未安装'=>false]，当data的值为true则显示已安装
     * @return ListBuilder
     */
    public function keyText($name, $title,$map = null) {
        $getMap = $this->createGetMap($map,$name);
        return $this->key($name, $title, 'text',['getMap'=>$getMap]);
    }

    /**
     * @param $name string 数据键名
     * @param $title string 表格标题
     * @param $getUrl string 例如: Url::build('index',['id'=>'###']); 然后###就会替换成name的值
     * @param $text string 超链接的文字内容
     * @return ListBuilder
     */
    public function keyLink($title, $getUrl, $text = '',$name = 'id') {
        $getUrl = $this->createGetUrl($getUrl,$name);
        return $this->key($name,$title,'link',['getUrl'=>$getUrl,'text'=>$text]);
    }
    public function keyUrlImage($name,$title) {
        return $this->key($name,$title,'urlImage');
    }
    public function keyImage($name,$title) {
        return $this->key($name,$title,'image');
    }
    public function keyMultiImage($name,$title) {
        return $this->key($name,$title,'multiImage');
    }

    /**
     * @param $getUrl
     * @param null $getText
     * @param bool $ajaxPost
     * @param string $title
     * @param string $name 替换url ### 的name
     * @return $this
     * @internal param null $getTextMap
     */
    public function keyDoAction($getUrl,$getText = null,$ajaxPost = true, $title = '操作', $name = 'id') {
        $getUrl = $this->createGetUrl($getUrl,$name);
        $getMap = $this->createGetMap($getText);

        $doAction = null;

        // 看看前面是否已经添加过
        foreach ($this->_keyList as &$key) {
            if($key['type'] == 'doAction') {
                $doAction = &$key;
                break;
            }
        }

        // 是否ajax
        $class = '';
        if($ajaxPost) {
            $class .= 'ajax-post';
        }

        // 一个操作html的数据
        $action = [
            'attr'=>[
                'class'=>$class,
            ],
            'name'=>$name,
            'getUrl'=>$getUrl,
            'getMap'=>$getMap,
        ];

        if($doAction) {
            // 如果添加过
            $doAction['opt']['actions'][] = $action;
        }else {
            // 如果没有添加过
            $this->key(null,$title,'doAction',[
                'actions'=>[$action]
            ]);
        }

        return $this;
    }

    /**
     * @param $title
     * @param $attr
     * @return ListBuilder
     */
    public function button($title,$attr) {
        $this->_buttonList[] = [
            'title' => $title,
            'attr' => $attr
        ];
        return $this;
    }

    /**
     * @param $href
     * @param string $title
     * @param array $attr
     * @return ListBuilder
     */
    public function buttonNew($href,$title="新增",$attr=[]) {
        $attr['href'] = $href;
        $attr['class'] = 'btn btn-success btn-a';
        return $this->button($title,$attr);
    }

    public function buttonDelete($url,$title="删除",$attr=[]) {
        $attr['url'] = $url;
        $attr['class'] = 'btn btn-danger ajax-post-ids';
        $attr['type'] = 'button';
        return $this->button($title,$attr);
    }
    public function buttonBack($title = '返回')
    {
        $attr = array();
        $attr['onclick'] = 'javascript:history.back(-1);return false;';
        $attr['class'] = 'btn btn-default';
        $attr['type'] = 'button';
        return $this->button($title, $attr);
    }

    public function pagination($totalCount, $listRows) {
        $page = $this->_request->param('page');
        $this->_pagination = new Pagination($page,$totalCount,$listRows,urldecode(Url::build($this->_request->action(),array_merge(['page'=>"###"],$_GET))));
        return $this;
    }


    public function setSearchUrl($url) {
        $this->_searchUrl = $url;
        return $this;
    }

    /**
     * @param string $title 搜索框的标题
     * @param string $name  搜索后，get请求url上的key名称
     * @param string $desc  这个搜索的描述，而不是排序
     * @param string $type  input 的type值
     * @return $this
     */
    public function search($title="搜索",$name="key",$desc='',$type='text') {
        $this->_searchList[] = [
            'title' => $title,
            'name' => $name,
            'desc' => $desc,
            'type' => $type
        ];
        return $this;
    }

    public function setSelectUrl($url) {
        $this->_selectUrl = $url;
        return $this;
    }

    /**
     * @param $title string
     * @param $name string
     * @param $options array    选择框的内容，例如: [0=>'全部',1=>'大',2=>'中',3=>'小','other'=>'其他']
     * @param string $desc string
     * @return $this
     */
    public function select($title="筛选",$name="key",$options=[],$desc = '') {
        $this->_selectList[] = [
            'title' => $title,
            'name' => $name,
            'options'=>$options,
            'desc' => $desc
        ];
        return $this;
    }

    private function createGetUrl($url,$name = 'id') {
        if(is_string($url)) {
            return function ($data) use($url,$name) {
                return str_replace('###',$data[$name],$url);
            };
        }else {
            return $url;
        }
    }
    private function createGetMap($getMap,$name = null) {
        if(is_array($getMap) || $getMap == null) {
            return function ($value) use ($getMap,$name) {
                if(is_array($getMap) && $name) {
                    foreach ($getMap as $map => $val) {
                        if($val == $value[$name]) {
                            return $map;
                        }
                    }
                }
                return $value[$name];
            };
        }else if(is_string($getMap)){
            return function ($value) use ($getMap) {
                return $getMap;
            };
        }else {
            return $getMap;
        }

    }
}